package com.hm.cms.websit;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hm.cms.def.WyCtoItemTypeEnum;
import com.hm.cms.service.ArticleService;
import com.hm.cms.service.TermsService;
import com.hm.cms.util.WebSitUtil;
import com.hm.cms.vo.HcmsArticleVo;
import com.hm.cms.vo.HcmsTermsVo;
import com.hm.common.network.httpclient.HttpClientFactory;
import com.hm.common.network.httpclient.HttpClientResponseParse;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.StringUtil;
import com.hm.common.util.WebUtil;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午2:14:58 2017年11月9日
 * @version 1.0
 * @describe 
 */
@Slf4j
@Component
public class WyCtoHandler {

	private static int timeout = 3000000;
	
	@Autowired
	private TaskExecutor taskExecutor;
	
	@Autowired
	private TermsService termsService;
	
	@Autowired
	private ArticleService articleService;
	
	public void handler() {
		try {
			for(WyCtoItemTypeEnum itemType : WyCtoItemTypeEnum.values()){
				taskExecutor.execute(new Runnable() {
					
					@Override
					public void run() {
						List<Integer> types = itemType.getType();
						for(Integer type:types){
							for (int i = 3; i >= 1; i --) {
								try {
									loadArticleMulu(i, type, "1", itemType.getTermTaxonomy());
								} catch (Exception e) {
									log.error(e.getMessage());
								}
							}
						}
					}
				});
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	private void loadArticleDetail(String title, String uri, String operationUserId, String tagId) throws Exception {
		try {
			if (articleService.checkArticleSourceUri(uri)) {
				return;
			}

			Document document = Jsoup.connect(uri).data("query", "Java").userAgent("Mozilla").cookie("auth", "token").timeout(timeout).get();

			Elements element = document.getElementsByClass("zwnr");
			element.get(0).getElementsByTag("h2").remove();
			Elements elements = element.get(0).getElementsByTag("div");
			element.get(0).getElementsByTag("ol").remove();
			elements.last().remove();
			element.get(0).getElementsByClass("dzdz").remove();
			element.get(0).getElementsByClass("guanggao").remove();

			String keyStr = document.select("meta[name=keywords]").get(0).attr("content");

			String html = element.get(0).html();

			List<String> termIds = new ArrayList<String>();
			String[] keys = keyStr.split(",");
			for (String key : keys) {
				HcmsTermsVo hcmsTermsVo = termsService.getHcmsTermsByTermName(key);
				if (CommonUtil.isNotEmpty(hcmsTermsVo)) {
					termIds.add(hcmsTermsVo.getId());
					continue;
				}

				HcmsTermsVo termsVo = new HcmsTermsVo();
				termsVo.setTermName(key);
				termsVo.setTermCode(key);
				termsVo.setTermOrder(-1);
				termIds.add(termsService.addTerms(termsVo, operationUserId));
			}

			HcmsArticleVo articleVo = new HcmsArticleVo();
			{
				articleVo.setTermIds(termIds);
				articleVo.setTermTayIds(Arrays.asList(tagId));
				articleVo.setArticleContent(html);
				articleVo.setAuthorName("网络采集");
				articleVo.setReleaseTime(System.currentTimeMillis());
				articleVo.setTitle(title);
				articleVo.setKeywords(keyStr);
				articleVo.setSourceName("51CTO");
				articleVo.setSourceUri(uri);
				articleVo.setArticleOrder((int) articleService.getArtilcleMaxOrder());
				articleVo.setArticleExcerpt(StringUtil.dislodgeAllBlank(WebUtil.clearHtmlTags(html)).substring(0, 200));
			}
			articleService.addArticle(articleVo, operationUserId);

		} catch (Exception e) {
			this.loadArticleDetail_v2(title, uri, operationUserId, tagId);
			log.error(e.getMessage());
		}

	}
	
	private void loadArticleDetail_v2(String title, String uri, String operationUserId,String tagId) throws Exception {
		try {
			if (articleService.checkArticleSourceUri(uri)) {
				return;
			}

			Document document = Jsoup.connect(uri).data("query", "Java").userAgent("Mozilla").cookie("auth", "token").timeout(timeout).get();

			String keyStr = document.select("meta[name=keywords]").get(0).attr("content");

			Element element = document.getElementById("content");
			element.getElementsByClass("page").remove();
			element.getElementsByClass("docu").remove();
			element.getElementsByClass("f12").remove();
			element.getElementsByClass("blank10").remove();
			element.getElementsByClass("blank1").remove();
			String html = element.html();

			List<String> termIds = new ArrayList<String>();
			String[] keys = keyStr.split(",");
			for (String key : keys) {
				HcmsTermsVo hcmsTermsVo = termsService.getHcmsTermsByTermName(key);
				if (CommonUtil.isNotEmpty(hcmsTermsVo)) {
					termIds.add(hcmsTermsVo.getId());
					continue;
				}

				HcmsTermsVo termsVo = new HcmsTermsVo();
				termsVo.setTermName(key);
				termsVo.setTermCode(key);
				termsVo.setTermOrder(-1);
				termIds.add(termsService.addTerms(termsVo, operationUserId));
			}

			HcmsArticleVo articleVo = new HcmsArticleVo();
			{
				articleVo.setTermIds(termIds);
				articleVo.setTermTayIds(Arrays.asList(tagId));
				articleVo.setArticleContent(html);
				articleVo.setAuthorName("王小林");
				articleVo.setReleaseTime(System.currentTimeMillis());
				articleVo.setTitle(title);
				articleVo.setKeywords(keyStr);
				articleVo.setSourceName("51CTO");
				articleVo.setSourceUri(uri);
				articleVo.setArticleOrder((int) articleService.getArtilcleMaxOrder());
				articleVo.setArticleExcerpt(StringUtil.dislodgeAllBlank(WebUtil.clearHtmlTags(html)).substring(0, 200));
			}
			articleService.addArticle(articleVo, operationUserId);

		} catch (Exception e) {
			System.out.println("#########错误页面地址########>"+uri);
			log.error(e.getMessage(),e);
		}
	}
	
	public static void main(String[] args) throws Exception{
		//http://ai.51cto.com/art/201706/542840.htm
	}
	
	
	private void loadArticleMulu(int pageNumber, int typeId, String operationUserId,String tagId) throws Exception {
		String jsonpTag = "jsonp1509334907443";

		HttpResponse response = HttpClientFactory.GET.build("http://other.51cto.com/php/get_channel_recommend_art_list.php?callback=" + jsonpTag + "&page="
				+ pageNumber + "&type_id=" + typeId + "&type=recommend&page_size=19").execute();
		String parse = HttpClientResponseParse.parse(response);
		List<WyCtoCallback> callbacks = JSON.parseObject(parse.substring(jsonpTag.length() + 2, parse.length() - 4),
				new TypeReference<List<WyCtoCallback>>() {
				});
		for (WyCtoCallback callback : callbacks) {
			loadArticleDetail(callback.getTitle(), callback.getUrl(), operationUserId, tagId);
			WebSitUtil.wating3();
		}
	}

	
	@Data
	public static class WyCtoCallback implements Serializable {

		private static final long serialVersionUID = 1L;

		private Integer msg;

		private String ID;

		private String title;

		private String picname;

		private String url;

		private String stime;

		private String typeid;

		private String thumb;

		private String has_thumb;

		private String info;

		private String keywords;

		private String typename;

		private String typedomain;

	}
}
